package cn.itcast.order.Tools;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

import cn.itcast.order.R;
import cn.itcast.order.ui.LoginActivity;

public class DishAdapter extends ArrayAdapter<Dish> {

    Context context;
    DataDB db;
    DataTools d_tools;
    List<Dish> list = new ArrayList<>();

    public DishAdapter(@NonNull Context context, int resource, List<Dish> data) {
        super(context, resource,data);
        this.context = context;
        db = new DataDB(context,"Data.db",null,1);
        d_tools = new DataTools(db);
        this.list = data;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View view;
        ViewHolder holder;
        if (convertView == null){
            view = LayoutInflater.from(context).inflate(R.layout.item_dish,parent,false);
            TextView name = view.findViewById(R.id.name);
            ImageView image = view.findViewById(R.id.image);
            Button add = view.findViewById(R.id.add);
            holder = new ViewHolder(name,image,add);
            view.setTag(holder);
        }else {
            view = convertView;
            holder = (ViewHolder)view.getTag();
        }
        Dish tools = getItem(position);
        if (tools != null){
            holder.name.setText(tools.name);
            holder.image.setImageResource(tools.image);
        }
        holder.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!d_tools.select(LoginActivity.account,list.get(position).name)){
                    d_tools.insert(LoginActivity.account,list.get(position).name,
                            list.get(position).image,
                            list.get(position).message);
                    Toast.makeText(context,"加入成功",Toast.LENGTH_SHORT).show();
                }else {

                    Toast.makeText(context,"已存在于菜单",Toast.LENGTH_SHORT).show();
                }
            }
        });

        return view;
    }


    public class ViewHolder{

        public TextView name;
        public ImageView image;
        public Button add;

        public ViewHolder(TextView name,ImageView image,Button add){
            this.image = image;
            this.name = name;
            this.add = add;
        }
    }
}
